<script lang="ts" setup>
import { reactive, ref } from 'vue'
import api from '/@/api/email/index';
import { type FormInstance, type FormRules } from 'element-plus'
import OneIcon from '/@/components/Common/OneIcon.vue'

defineProps({
    modelValue: {
        type: Boolean,
        default: false
    },
})
const emit = defineEmits(['update:modelValue', 'refresh'])
const ruleFormRef = ref<FormInstance>()
interface RuleForm {
    id: number | undefined
    cardNumber: string
    expires: string
    code: string
    companyCode: string
    piList: {
        pi: string
        amount: number
        payAttribute: number
    }[]
    amount: number | undefined
    remark: string
}

const companyOptions = ref<{
    code: string
    name: string
}[]>([])
const ruleForm = reactive<RuleForm>({
    id: undefined,
    cardNumber: '',
    expires: '',
    code: '',
    companyCode: '',
    piList: [{
        pi: '',
        amount: 0,
        payAttribute: 1,
    }],
    amount: undefined,
    remark: '',

})
const rules = reactive<FormRules<RuleForm>>({
    cardNumber: [{ required: true, message: '请输入卡号', trigger: 'blur' }],
    expires: [{ required: true, message: '请输入过期日期', trigger: 'blur' }],
    code: [{ required: true, message: '请输入安全码', trigger: 'blur' }],
    companyCode: [{ required: true, message: '请选择平台', trigger: 'blur' }],
    amount: [{ required: true, message: '请输入金额', trigger: 'blur' }],
})
function add() {
    ruleForm.piList.push({
        pi: '',
        payAttribute: 1,
        amount: 0,
    })
}
function remove(key: number) {
    ruleForm.piList.splice(key, 1)
}
const remoteLoading = ref(false)
const piData = ref<{
    pi: string
}[]>([])
async function remoteMethod(query: any, init = false) {
    if (query || init) {
        remoteLoading.value = true
        try {
            const { data } = await api.pi.piList({
                excludeGp: 0,
                withPi: 1,
                pi: query,
            })
            piData.value = data
            remoteLoading.value = false
        }
        catch (error) {
            console.error(error)
            remoteLoading.value = false
        }
    }
    else {
        piData.value = []
    }
}
async function remoteCardNumberMethod(query: any, cb: (arg: any) => void) {
    try {
        const { data } = await api.cardApply.listCards({
            cardNumber: query,
        })
        cb(data)
    }
    catch (error) {
        console.error(error)
    }
}
const getInfo = async (id: number) => {
    try {
        const { data } = await api.cardApply.info(id)
        console.log('详情数据', data)
        if (!data.piList) {
            data.piList = [{
                pi: '',
                payAttribute: 1,
                usdAmount: 0,
            }]
        }
        Object.assign(ruleForm, data)
    } catch (error) {
        console.log(error)
    }
}
const submit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            const obj = { ...ruleForm }
            const { code } = await (obj.id ? api.cardApply.edit(obj) : api.cardApply.add(obj))
            if (code === 200) {
                ElMessage.success('操作成功')
                emit('refresh')
                close()
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}
const close = () => {
    ruleFormRef.value?.resetFields()
    emit('update:modelValue', false)
}
const getCompanyOptions = () => {
  api.pi.companyList().then((res:any) => {
    companyOptions.value = res.data;
  })
}
getCompanyOptions()
defineExpose({
    getInfo,
    ruleForm
})
</script>
<template>
    <TwoDialog id="voucherClaim" :modelValue="modelValue" title="刷卡申请" width="1366px" @submit="submit(ruleFormRef)"
        @close="close" @minimize="emit('update:modelValue', false)">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto">
            <el-row :gutter="16">
                <el-col :span="8">
                    <el-form-item label="卡号" prop="cardNumber">
                        <el-autocomplete
                            v-model="ruleForm.cardNumber"
                            :fetch-suggestions="remoteCardNumberMethod"
                            value-key="cardNumber"
                            placeholder="输入卡号可以搜索"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="过期日期" prop="expires">
                        <el-date-picker v-model="ruleForm.expires" placeholder="请选择日期" value-format="YYYY-MM-DD" style="width: 100%;" type="date" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="安全码" prop="code">
                        <el-input v-model="ruleForm.code" placeholder="请输入安全码" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="选择平台" prop="companyCode">
                        <el-select v-model="ruleForm.companyCode" placeholder="请选择公司">
                            <el-option v-for="item in companyOptions" :key="item.code" :label="item.name" :value="item.code" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-divider>如果多个PI一起刷卡，这里可以添加多个</el-divider>
                <el-col :span="24">
                    <el-row v-for="(form, key) in ruleForm.piList" :key="key">
                        <el-col :span="12">
                            <el-form-item label="PI" prop="pi">
                                <el-space>
                                    <el-select
                                        v-model="form.pi"
                                        placeholder="输入PI号搜索"
                                        filterable
                                        remote
                                        :remote-method="remoteMethod"
                                        :loading="remoteLoading"
                                        clearable
                                    >
                                        <el-option v-for="item in piData" :key="item.pi" :label="item.pi" :value="item.pi" />
                                    </el-select>
                                    <span>默认显示最新录入的PI号，输入PI号可以搜索指定PI</span>
                                </el-space>
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                            <el-form-item label="刷卡金额" prop="usdAmount">
                                <el-input-number v-model="form.amount" :min="0" :controls="false" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="类型" prop="payAttribute">
                                <el-space>
                                    <el-radio-group v-model="form.payAttribute">
                                        <el-radio label="全款" :value="1" />
                                        <el-radio label="定金" :value="2" />
                                        <el-radio label="尾款" :value="3" />
                                    </el-radio-group>
                                    <el-button v-if="key === 0" circle @click="add">
                                        <OneIcon name="ep:plus" />
                                    </el-button>
                                    <el-button v-else circle @click="remove(key)">
                                        <OneIcon name="ep:minus" />
                                    </el-button>
                                </el-space>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="总刷卡金额" prop="amount">
                        <el-input-number v-model="ruleForm.amount" placeholder="请输入总刷卡金额" :min="0" :controls="false" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="备注" prop="remark">
                        <el-input v-model="ruleForm.remark" type="textarea" placeholder="请输入备注" />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </TwoDialog>
</template>
<style lang="scss" scoped>
.cascader-panel {
    width: fit-content;
}
.el-form-item .el-form-item {
    margin-bottom: 18px;
}
</style>